from django.conf import settings
from django.db import transaction
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import Brand
from apps.meiduo_admin.serializers.goods_brands_serializers import BrandsSerializer
from apps.meiduo_admin.utils.pagenum import PageNum
from rest_framework.request import Request
from rest_framework import serializers

class GoodsBrands(ModelViewSet):
    serializer_class = BrandsSerializer
    queryset = Brand.objects.all().order_by("-create_time")
    pagination_class = PageNum

    def create(self, request, *args, **kwargs):
        # 接受数据
        logo = request.data.get("logo")
        name = request.data.get("name")
        first_letter = request.data.get("first_letter")
        # print(request.data)
        # print(name,type(name))
        # < QueryDict: {'name': ['AA萨达萨达'], 'first_letter': ['A'], 'logo': [ < InMemoryUploadedFile: yang.png( image / png) >]} >
        # AA萨达萨达 <class 'str'>
        # 验证数据
        if not all([logo]):
            return Response({"detial": "数据不完整"}, status=400)
        # 创建Fdfs对象
        image_client = Fdfs_client(settings.FASTDFS_PATH)
        # 上传图片   文件不在本地时用upload_by_buffer
        data = image_client.upload_by_buffer(logo.read())
        image_url = data.get("Remote file_id")
        logo=image_url
        # 创建模型类对象
        instance = Brand.objects.create(name=name,logo=logo,first_letter=first_letter)
        seriazlier = self.get_serializer(instance)
        return Response(seriazlier.data, status=201)
    def update(self, request, *args, **kwargs):
        # 获取想要修改的对象
        instance = self.get_object()
        # 接受数据
        image = request.data.get("logo")
        name = request.data.get("name")
        first_letter = request.data.get("first_letter")
        # print(instance.id)
        # 验证
        if not all([name,first_letter]):
            return Response({"detial": "数据不完整"}, status=400)
        # 禁止自动提交
        with transaction.atomic():
            # 开启事务
            sid = transaction.savepoint()
            try:
            # 创建Fdfs对象
                image_client = Fdfs_client(settings.FASTDFS_PATH)
                # image_client.delete_file(instance.logo.name)
                image_client.delete_file(instance.logo.name)
                # 上传图片   文件不在本地时用upload_by_buffer
                data = image_client.upload_by_buffer(image.read())
                logo = data.get("Remote file_id")
                # 创建模型类对象
                instance = Brand.objects.get(id=instance.id)
                instance.name = name
                instance.logo = logo
                instance.first_letter = first_letter
                instance.save()
            except:
                # 捕获异常，说明数据库操作失败，进行回滚
                transaction.savepoint_rollback(sid)
                raise serializers.ValidationError('数据库错误')
            else:
                serializer = self.get_serializer(instance)
                return Response(serializer.data)

    # 图片的删除
    def destroy(self, request, *args, **kwargs):
        # 查询当前对象
        instance = self.get_object()
        # 删除图片
        image_client = Fdfs_client(settings.FASTDFS_PATH)
        image_client.delete_file(instance.logo.name)
        # 删除数据
        instance.delete()
        return Response(status=204)